<template>
  <div class="app-container">
    <!--条件搜索表单-->
    <el-row>
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="searchObj.name" placeholder="用户名" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchObj.email" placeholder="邮箱" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchObj.sex" placeholder="性别" @change="getAll()">
            <el-option value="男" label="男" />
            <el-option value="女" label="女" />
            <el-option value="未知" label="未知" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchObj.roleId" placeholder="身份" @change="getAll()">
            <el-option value="1" label="管理员" />
            <el-option value="2" label="教师" />
            <el-option value="3" label="学生" />
          </el-select>
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getAll()">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reset()">清空</el-button>
      </el-form>
    </el-row>

    <!-- 工具栏 -->
    <el-row>
      <el-button type="primary" icon="el-icon-plus" @click="openEdit(null)">新增</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="batchDelete">批量删除</el-button>
    </el-row>

    <el-row>
      <!-- banner列表 :data="list"表示遍历list数组 stripe条纹 -->
      <el-table
        :data="page.list"
        :border="false"
        v-loading="loading"
        element-loading-text="正在努力加载数据中..."
        stripe
        style="width: 100%; margin: 15px 0px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" fixed="left" width="55" />
        <el-table-column type="index" fixed="left" width="80" label="序号" />
        <el-table-column prop="userName" fixed="left" label="账号" />
        <el-table-column prop="trueName" label="昵称" show-overflow-tooltip />
        <el-table-column prop="userSex" label="性别" show-overflow-tooltip />
        <el-table-column prop="userEmail" label="邮箱" show-overflow-tooltip />
        <el-table-column prop="roleId" label="身份" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tag v-if="scope.row.roleId === 1" type="success">管理员</el-tag>
            <el-tag v-if="scope.row.roleId === 2" type="primary">教师</el-tag>
            <el-tag v-if="scope.row.roleId === 3" type="info">学生</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createAt" label="创建人" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip />
        <el-table-column prop="updateAt" min-width="100" label="最后修改人" show-overflow-tooltip />
        <el-table-column prop="updateTime" min-width="120" label="最后修改时间" show-overflow-tooltip />

        <!-- 操作 -->
        <el-table-column label="操作" fixed="right" width="250" align="center">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="remove(scope.row.id)" :disabled="userId == scope.row.id"
              >删除</el-button
            >
            <el-button type="success" size="mini" @click="openEdit(scope.row.id)" :disabled="userId == scope.row.id"
              >编辑</el-button
            >
            <el-button type="primary" size="mini" @click="resetPwd(scope.row.id)" :disabled="userId == scope.row.id"
              >重置密码</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <!-- 分页导航栏 -->
    <el-row>
      <el-pagination
        background
        :current-page="pIndex"
        :page-size="pSize"
        :total="page.total"
        :page-sizes="[3, 6, 9, 12, 15]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        @current-change="getAll"
        @size-change="handleSizeChange"
      />
    </el-row>

    <!-- 表单 -->
    <el-dialog :title="user.id ? '用户修改' : '用户新增'" :visible.sync="visible" :before-close="close">
      <el-form ref="userForm" label-width="100px" :model="user" :rules="rules">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="ID" prop="id" :hidden="true">
              <el-input v-model="user.id" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户账号:" prop="userName">
              <el-input v-model.trim="user.userName" placeholder="请输入账号" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户昵称:" prop="trueName">
              <el-input v-model.trim="user.trueName" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item v-if="!user.id" label="用户密码:" prop="password">
              <el-input v-model.trim="user.password" type="password" placeholder="请输入密码" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户性别:" prop="userSex">
              <el-select v-model="user.userSex" style="width: 100%" placeholder="性别">
                <el-option value="男" label="男" />
                <el-option value="女" label="女" />
                <el-option value="未知" label="未知" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户邮箱:" prop="userEmail">
              <el-input v-model.trim="user.userEmail" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="用户身份:" prop="roleId">
              <el-select v-model="user.roleId" placeholder="请选择身份" style="width: 100%">
                <el-option v-for="item in role" :key="item.id" :label="item.roleName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button @click="resetForm">重 置</el-button>
        <el-button type="primary" @click="save('userForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入api接口定义的js文件
import userApi from '@/api/sys/user'
import user from '@/store/modules/user'

export default {
  data() {
    return {
      // 列表相关
      pIndex: 1,
      pSize: 6,
      searchObj: {},
      loading: true,
      page: [],
      ids: [],
      userId: '',

      // 表单相关
      visible: false,
      user: {
        id: undefined,
        userName: '',
        trueName: '',
        password: '',
        userSex: '未知',
        userEmail: '',
        roleId: ''
      },
      role: [
        { id: 1, roleName: '管理员' },
        { id: 2, roleName: '教师' },
        { id: 3, roleName: '学生' }
      ],
      rules: {
        userName: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          { min: 5, message: '账号不能少于5位', trigger: 'blur' }
        ],
        trueName: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        userEmail: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入有效的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        roleId: [{ required: true, message: '请选择身份', trigger: 'change' }]
      }
    }
  },
  created() {
    // 勾子函数，在页面渲染之前执行，一般调用methods定义的方法得到数据
    this.getAll() // 调用methods中的函数
    this.userId = sessionStorage.getItem('userId')
  },
  methods: {
    // 用户信息
    getAll(current = 1) {
      this.loading = true
      // 加载列表数据
      this.pIndex = current //添加当前页参数
      // axios异步获取远程数据（ajax），通过api
      userApi
        .getPage(this.pIndex, this.pSize, this.searchObj)
        .then((response) => {
          this.page = response.data
          this.loading = false
        })
        .catch((error) => {
          this.loading = false
          //请求失败
          console.log(error)
        })
    },

    // 改变页码
    handleSizeChange(pageSize) {
      this.pSize = pageSize
      // 重新调用数据加载方法 --> 方法中已经加入的查询参数
      this.getAll()
    },

    // 复选框选中
    handleSelectionChange(r) {
      // 得到选中的id
      this.ids = r.map((v) => v.id)
    },

    // 删除用户信息
    remove(id) {
      this.$confirm('此操作将永久删除用户信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确定执行then方法
        // 调用接口
        userApi.remove(id).then((resp) => {
          // 提示
          this.$message.success('删除成功!')
          // 刷新页面
          this.getAll()
        })
      })
    },

    // 打开表单
    async openEdit(id) {
      if (id != null) {
        this.getById(id)
      }

      this.visible = true
    },

    // 根据Id查询用户
    getById(id) {
      userApi.getById(id).then((res) => {
        this.user = res.data
      })
    },

    // 关闭表单
    close() {
      this.visible = false
      this.$refs['userForm'].resetFields()
    },

    // 批量删除
    batchDelete() {
      if (this.ids.length > 0) {
        let userId = sessionStorage.getItem('userId')
        if (this.ids.includes(parseInt(userId))) {
          this.$message.warning('不能删除当前登录用户')
        } else {
          this.$confirm('此操作将永久删除用户信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 确定执行then方法
            // 调用接口
            userApi.batchRemove(this.ids).then((resp) => {
              // 提示
              this.$message.success('删除成功!')
              // 刷新页面
              this.getAll()
            })
          })
        }
      } else {
        this.$message.warning('请至少选择一条数据')
      }
    },

    // 保存
    save(form) {
      // 表单校验
      this.$refs[form].validate((valid) => {
        if (valid) {
          const apiCall = this.user.id ? userApi.update(this.user) : userApi.save(this.user)
          apiCall.then(() => {
            this.$message.success('操作成功')
            this.close()
            this.getAll()
          })
        }
      })
    },

    // 重置密码
    resetPwd(id) {
      this.$confirm('此操作将重置用户密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userApi.resetPwd(id).then((res) => {
          this.$message.success('操作成功')
        })
      })
    },

    // 重置表单
    resetForm() {
      if (this.user.id) {
        this.getById(this.user.id)
      }
      this.$refs['userForm'].resetFields()
    },

    // 清空
    reset() {
      this.searchObj = {}
      this.getAll()
    }
  }
}
</script>

<style></style>
